<template>
    <!-- 新增/编辑电子围栏 -->
    <div class="container">
        <div class="fence">
            <div id="fence"></div>
            <div class="searchAddress">
                <Input search enter-button placeholder="请输入准确的项目地址"  style="width:300px"  @on-search="searchAddress" v-model="address" clearable/>
            </div>
            <div class="box" v-if="sub == 1&&id">
                <el-button type="primary" @click="edit"  size="small" plain >开始编辑</el-button>
                <el-button type="primary" @click="end"  size="small" plain >结束编辑</el-button>
            </div>
        </div>
        <div class="right">
            <div class="ipt">
                <span>项目名称:</span>
                <Input v-model="deptName" disabled style="width:180px" />
            </div>
            <div class="ipt">
                <span>电子围栏名称:</span>
                <Input :maxlength="30" v-model="name" placeholder="请输入电子围栏名称" style="width:180px" />
            </div>
            <div class="top">
                <input type="radio" name="func" value="polygon" />
                <span class="input-text" style="width:70px;">画多边形</span>
                <input type="radio" name="func" value="circle" />
                <span class="input-text">画圆</span>
            </div>
            <div class="isShow" v-show="sub == 1">
                点击鼠标“左键”开始绘图，点击鼠标“右键”或“双击左键”结束绘图
            </div>
            <div class="center">
                <p v-show="sub !== 0">
                    <span>经度</span>
                    <span>纬度</span>
                </p>
                <div v-for="(item,index) in polygon" :key="index" v-show="sub == 1">
                    <Input v-model="item.lng" placeholder="请输入经度" style="width:80px" clearable />
                    <Input v-model="item.lat" placeholder="请输入纬度" style="width:80px ;margin-right:10px;margin-left:10px;" clearable />
                    <el-button @click="removeRow(index)" :disabled="polygon.length == 3" :type="polygon.length == 3?'info':'danger'" size="small" plain>删除</el-button>
                </div>
                <div v-show="sub == 2">
                    <Input v-model="radius" placeholder="请输入半径" style="width:200px" clearable />
                </div>
                <div v-show="sub == 2">
                    <Input v-model="center.lng" placeholder="请输入半径" style="width:80px" clearable />
                    <Input v-model="center.lat" placeholder="请输入半径" style="width:80px;margin-left:10px" clearable />
                </div>
                <p v-if="sub !== 0">
                    <el-button type="primary" @click="addRow" style="margin-right:20px" size="small" plain v-if="sub == 1">加点</el-button>
                    <el-button type="primary" @click="drawArea" style="margin-right:20px" size="small" plain>绘制</el-button>
                </p>
            </div>
            <div class="bottom">
                <el-button type="info" @click="goBack" style="margin-right:20px" size="small" plain>返回</el-button>
                <el-button type="primary" @click="sumbit" style="margin-right:20px" size="small" plain>保存</el-button>
            </div>
        </div>

    </div>
</template>

<script>
import {getFenceAdd, getWorkAreaAdd, getWorkAreaEdit} from "@/api/api.js";
import {getEquipFencetAdd} from "@/api/equip.js"
export default {
    data() {
        return {
            map: "",
            lng: "",
            lat: "",
            deptName: "",
            deptId: "",
            name: "",
            province: "",
            citySelect: "",
            districtSelect: "",
            areaSelect: "",
            district: "",
            citycode: "",
            polygons: [],
            sub: 0,
            cover: "",
            polygon: [
                { lat:"", lng:"" },
                { lat:"", lng:"" },
                { lat:"", lng:"" }
            ],
            radius: "",
            center: {},
            id: "",
            isAdd: false,
            address:"",
            markerFlag:true,
            markerList:[],
        };
    },
    watch: {
        //缓存上一次的区域
        sub(val, oldVal) {
            if (val == 1) {
                if (this.polygon[0].lat !== "" && this.polygon[0].lng !== "") {
                    this.map.clearMap();
                    var path = [];
                    for (let i = 0; i < this.polygon.length; i++) {
                        //多边形的坐标点
                        let x = [this.polygon[i].lng, this.polygon[i].lat];
                        path.push(x);
                    }
                    this.cover = new AMap.Polygon({
                        path: path,
                        strokeColor: "#ff00ff",
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.4,
                        fillColor: "#ff00ff",
                        zIndex: 50,
                    });
                    this.cover.setMap(this.map);
                    // 缩放地图到合适的视野级别
                    this.map.setFitView(this.cover);
                }
            } else if (val == 2) {
                if (this.radius !== "" && this.radius !== undefined) {
                    this.map.clearMap();
                    this.cover = new AMap.Circle({
                        center: [this.center.lng, this.center.lat],
                        radius: this.radius, //半径
                        borderWeight: 3,
                        strokeColor: "#ff00ff",
                        strokeOpacity: 1,
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.4,
                        strokeStyle: "dashed",
                        strokeDasharray: [10, 10],
                        // 线样式还支持 'dashed'
                        fillColor: "#ff00ff",
                        zIndex: 50,
                    });
                    this.cover.setMap(this.map);
                    // 缩放地图到合适的视野级别
                    this.map.setFitView(this.cover);
                }
            }
        },
    },
    methods: {
        searchAddress(){
            if(this.address == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请输入地址"
                });
                return;
            }
            var _that =this;
            AMap.service("AMap.Geocoder", function() {
                var geocoder = new AMap.Geocoder({
                    city: "", //城市设为北京，默认：“全国”
                });
                var marker = new AMap.Marker();
                geocoder.getLocation(_that.address, function(status, result) {
                    if (status === 'complete'&&result.geocodes.length) {
                        var lnglat = result.geocodes[0].location
                        marker.setPosition(lnglat);
                        _that.map.setFitView(marker);
                    }else{
                        _that.$Message.warning('根据地址查询位置失败');
                        // log.error('根据地址查询位置失败');
                    }
                });
            });

        },
        getMap() {
            this.lat = this.$store.state.porjectObject.lat == undefined?30.592335:this.$store.state.porjectObject.lat;
            this.lng = this.$store.state.porjectObject.lng == undefined?114.29484:this.$store.state.porjectObject.lng;
            this.map = new AMap.Map("fence", {
                zoom: 14,
                center: [this.lng, this.lat],
            });

            // 构造官方卫星、路网图层
            var satelliteLayer = new AMap.TileLayer.Satellite();
            var roadNetLayer = new AMap.TileLayer.RoadNet();
            // 批量添加图层
            this.map.add([satelliteLayer, roadNetLayer]);
            this.getDraw();
        },
        drawArea() {
            if (this.sub == 1) {
                this.map.clearMap();
                var path = [];
                for (let i = 0; i < this.polygon.length; i++) {
                    if ( this.polygon[i].lat == "" || this.polygon[i].lng == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "经纬度不能为空",
                        });
                    }
                    //多边形的坐标点
                    let x = [this.polygon[i].lng, this.polygon[i].lat];
                    path.push(x);
                }
                this.cover = new AMap.Polygon({
                    path: path,
                    strokeColor: "#ff00ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: "#ff00ff",
                    zIndex: 50,
                });
                this.cover.setMap(this.map);
            } else if (this.sub == 2) {
                if (this.radius == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "半径不能为空",
                    });
                }
                if (this.center.lng == "" || this.center.lat == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "经纬度不能为空",
                    });
                }
                this.map.clearMap();
                this.cover = new AMap.Circle({
                    center: [this.center.lng, this.center.lat],
                    radius: this.radius, //半径
                    borderWeight: 3,
                    strokeColor: "#ff00ff",
                    strokeOpacity: 1,
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    strokeStyle: "dashed",
                    strokeDasharray: [10, 10],
                    // 线样式还支持 'dashed'
                    fillColor: "#ff00ff",
                    zIndex: 50,
                });
                this.cover.setMap(this.map);
                // 缩放地图到合适的视野级别
                this.map.setFitView(this.cover);
            }
        },
        removeRow(index) {
            this.polygon.splice(index, 1);
        },
        addRow() {
            let obj = {
                lat: "",
                lng: "",
            };
            this.polygon.push(obj);
        },
        edit(){
            let _that = this;
            _that.markerList = [];
            // let midMarker= [];
            if(this.markerFlag) {
                _that.polygon.forEach((i,index)=>{
                    //中间点
                    // if(index != 0  && index != _that.polygon.length){
                    //     let lng =  (_that.polygon[index].lng + _that.polygon[index+1].lng)/2;
                    //     let lat =  (_that.polygon[index].lat + _that.polygon[index+1].lat)/2;
                    //     let obj ={
                    //         lng:lng,
                    //         lat:lat,
                    //     }
                    //     midMrker.push(obj);
                    // }
                    // midMarker.push(
                    //     {
                    //         lng:(_that.polygon[0].lng + _that.polygon[_that.polygon.length].lng)/2,
                    //         lat:(_that.polygon[0].lat + _that.polygon[_that.polygon.length].lat)/2,
                    //     }
                    // )
                    var marker = new AMap.Marker({
                        map: _that.map,
                        icon: new AMap.Icon({
                            // image: require("./../assets/images/marker_Circle.png"),
                            image:"https://webapi.amap.com/images/dd-via.png",
                            size: new AMap.Size(15, 15), //图标大小
                            imageSize: new AMap.Size(15, 15)
                        }),
                        id: index,
                        position: [i.lng, i.lat],
                        offset: new AMap.Pixel(-5, -5),
                        // 设置是否可以拖拽
                        draggable: true,
                        cursor: 'move',
                    });
                    _that.markerList.push(marker)
                    marker.on( "dragging", function(e){
                         if(e.target.Ce){
                            _that.polygon[e.target.Ce.id].lng =  e.lnglat.lng;
                            _that.polygon[e.target.Ce.id].lat =  e.lnglat.lat;
                         } else {
                            _that.polygon[e.target.De.id].lng =  e.lnglat.lng;
                            _that.polygon[e.target.De.id].lat =  e.lnglat.lat;
                         }

                        var path = [];
                        for (let item = 0; item < _that.polygon.length; item++) {
                            //多边形的坐标点
                            let x = [_that.polygon[item].lng, _that.polygon[item].lat];
                            path.push(x);
                        }
                        _that.map.remove(_that.cover);
                        _that.cover = new AMap.Polygon({
                            path: path,
                            strokeColor: "#ff00ff",
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            fillColor: "#ff00ff",
                            zIndex: 50,
                        });
                        _that.cover.setMap(_that.map);
                    })
                })
            }
            _that.markerFlag = false;
        },
        end(){
            this.markerFlag = true;
            this.markerList.forEach(i=>{
                this.map.remove(i);
            })

        },
        getDraw(type) {
            var radios = document.getElementsByName("func");
            var arr = [];
            var _that = this;
            var mouseTool = new AMap.MouseTool(this.map);
            mouseTool.on("draw", function (e) {
                if (type != "") {
                    _that.map.remove(_that.cover);
                }
                if (arr.length >= 1) {
                    _that.map.remove(arr);
                    arr.push(e.obj);
                } else {
                    arr.push(e.obj);
                }
                if (arr.length > 0) {
                    //记录多边形的点
                    if (arr[arr.length - 1].CLASS_NAME == "AMap.Polygon") {
                        var x =[];
                        let pathArr = arr[arr.length - 1].Ce ? arr[arr.length - 1].Ce.path : arr[arr.length - 1].De.path
                        for ( let i = 0; i < pathArr.length;  i++ ) {
                            let obj = {
                                lng: pathArr[i].lng,
                                lat: pathArr[i].lat,
                            };
                            x.push(obj);
                        }
                        _that.polygon =x;
                    }
                    if (arr[arr.length - 1].CLASS_NAME == "AMap.Circle") {
                        //记录圆形的圆心和半径
                        let pathCir = arr[arr.length - 1].Ce ? arr[arr.length - 1].Ce : arr[arr.length - 1].De
                        _that.radius =  pathCir.radius;
                        _that.center =  pathCir.center;
                    }
                }
            });
            function draw(type) {
                switch (type) {
                    case "polygon": {
                        mouseTool.polygon({
                            fillColor: "#ff00ff",
                            strokeColor: "#ff00ff",
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            //同Polygon的Option设置
                        });
                        break;
                    }
                    case "circle": {
                        mouseTool.circle({
                            fillColor: "#ff00ff",
                            strokeColor: "#ff00ff",
                            borderWeight: 3,
                            strokeOpacity: 1,
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            strokeStyle: "dashed",
                            strokeDasharray: [10, 10],
                            //同Circle的Option设置
                        });
                        break;
                    }
                }
            }
            for (var i = 0; i < radios.length; i += 1) {
                radios[i].onchange = function (e) {
                    draw(e.target.value);
                    if (e.target.value == "polygon") {
                        _that.sub = 1;
                    } else if (e.target.value == "circle") {
                        _that.sub = 2;
                    } else {
                        _that.sub = 0;
                    }
                };
            }
        },
        goBack() {
            if (localStorage.getItem("fenceFlag") == 1) {
                this.$router.push({ path: "/emp/fence" });
            } else if (localStorage.getItem("fenceFlag") == 2) {
               this.$router.push({ path: "/equip/fence" });
            }else if (localStorage.getItem("fenceFlag") == 3) {
                this.$router.push({ path: "/prj/area" });
            }
        },
        sumbit() {
            if (localStorage.getItem("fenceFlag") == 1) {
                //人员电子围栏
                if (this.id === "") {
                    this.isAdd = true;
                } else {
                    this.isAdd = false;
                }
                if (this.name == ""||this.name==undefined) {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请输入电子围栏名称",
                    });
                    return;
                }
                if (this.sub == 1) {
                    if (this.polygon[0].lng == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                } else if (this.sub == 2) {
                    if (this.radius == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                }
                let params = {};
                if (this.sub == 1) {
                    //多边形
                    let arr = [];
                    for (let i = 0; i < this.polygon.length; i++) {
                        let x = {
                            lng: this.polygon[i].lng,
                            lat: this.polygon[i].lat,
                        };
                        arr.push(x);
                    }
                    params = {
                        id: this.isAdd ? "" : this.id,
                        name: this.name,
                        deptId: this.deptId,
                        type: 1,
                        polygonPointList: arr,
                    };
                } else if (this.sub == 2) {
                    //圆形
                    params = {
                        id: this.isAdd ? "" : this.id,
                        name: this.name,
                        deptId: this.deptId,
                        type: 2,
                        radius: parseInt(this.radius),
                        centerPoint: {
                            lng: this.center.lng,
                            lat: this.center.lat,
                        },
                    };
                }
                getFenceAdd(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.$router.push({ path: "/emp/fence" });
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            } else if (localStorage.getItem("fenceFlag") == 2){
                //考勤设备电子围栏
                if (this.id === "") {
                    this.isAdd = true;
                } else {
                    this.isAdd = false;
                }
                if (this.name == ""||this.name==undefined) {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请输入电子围栏名称",
                    });
                    return;
                }
                if (this.sub == 1) {
                    if (this.polygon[0].lng == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                } else if (this.sub == 2) {
                    if (this.radius == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                }
                let params = {};
                if (this.sub == 1) {
                    //多边形
                    let arr = [];
                    for (let i = 0; i < this.polygon.length; i++) {
                        let x = {
                            lng: this.polygon[i].lng,
                            lat: this.polygon[i].lat,
                        };
                        arr.push(x);
                    }
                    params = {
                        fenceId: this.isAdd ? "" : this.id,
                        name: this.name,
                        projectId: this.deptId,
                        type: 1,
                        polygonPointList: arr,
                    };
                } else if (this.sub == 2) {
                    //圆形
                    params = {
                        fenceId: this.isAdd ? "" : this.id,
                        name: this.name,
                        projectId: this.deptId,
                        type: 2,
                        radius: parseInt(this.radius),
                        centerPoint: {
                            lng: this.center.lng,
                            lat: this.center.lat,
                        },
                    };
                }
                getEquipFencetAdd(params)
                    .then((res) => {
                        if (res.code == 200) {
                            this.$router.push({ path: "/equip/fence" });
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }else if (localStorage.getItem("fenceFlag") == 3){
                //考勤设备电子围栏
                if (this.id === "") {
                    this.isAdd = true;
                } else {
                    this.isAdd = false;
                }
                if (this.name == ""||this.name==undefined) {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请输入电子围栏名称",
                    });
                    return;
                }
                if (this.sub == 1) {
                    if (this.polygon[0].lng == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                } else if (this.sub == 2) {
                    if (this.radius == "") {
                        this.$Modal.warning({
                            title: "您有必填字段",
                            content: "请在地图上选择电子围栏",
                        });
                        return;
                    }
                }
                let params = {};
                if (this.sub == 1) {
                    //多边形
                    let arr = [];
                    for (let i = 0; i < this.polygon.length; i++) {
                        let x = {
                            lng: this.polygon[i].lng,
                            lat: this.polygon[i].lat,
                        };
                        arr.push(x);
                    }
                    params = {
                        workAreaId: this.isAdd ? "" : this.id,
                        name: this.name,
                        deptId: this.deptId,
                        fenceType: 1,
                        polygonPointList: arr,
                    };
                } else if (this.sub == 2) {
                    //圆形
                    params = {
                        workAreaId: this.isAdd ? "" : this.id,
                        name: this.name,
                        deptId: this.deptId,
                        fenceType: 2,
                        radius: parseInt(this.radius),
                        centerPoint: {
                            lng: this.center.lng,
                            lat: this.center.lat,
                        },
                    };
                }
                if(this.id){
                    getWorkAreaEdit(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.$router.push({ path: "/prj/area" });
                            } else {
                                this.$Message.warning(res.msg);
                            }
                        })
                        .catch((error) => {
                            console.log(error);
                        });
                }else{
                    getWorkAreaAdd(params)
                        .then((res) => {
                            if (res.code == 200) {
                                this.$router.push({ path: "/prj/area" });
                            } else {
                                this.$Message.warning(res.msg);
                            }
                        })
                        .catch((error) => {
                            console.log(error);
                        });
                }

            }
        },
    },
    mounted() {
        this.deptName = this.$store.state.porjectObject.name;
        if(localStorage.getItem("fenceFlag") == 1 || localStorage.getItem("fenceFlag") == 3){
            this.deptId = this.$store.state.porjectObject.deptId;
        } else if(localStorage.getItem("fenceFlag") == 2) {
            this.deptId = this.$store.state.porjectTree.deptId;
        }
        this.id = this.$route.query.fenceId;
        this.sub = this.$store.state.fence.type === undefined ? 0 : this.$store.state.fence.type;
        this.name = this.$store.state.fence.name;
        if (this.sub == 1) {
            this.polygon = this.$store.state.fence.polygonPointList;
        } else if (this.sub == 2) {
            this.center = this.$store.state.fence.centerPoint;
            this.radius = this.$store.state.fence.radius;
        }
        this.getMap();
    },
};
</script>

<style lang="less" scoped>
@import "./../assets/style/themeBase.less";

.container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: space-between;
    /deep/.el-button{
        margin-left: 0px !important;
    }
    .fence {
        width: calc(100% - 300px);
        height: 100%;
        position: relative;
        #fence {
            width: 100%;
            height: 100%;
            // position: relative;
        }
    }
    .right {
        width: 300px;
        height: 100%;
        background: #fff;
        position: relative;
        .top {
            width: 300px;
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
            input {
                margin-right: 10px;
                cursor: pointer;
            }
            span {
                margin-right: 30px;
            }
        }
        .isShow {
            width: 200px;
            margin: 0 auto;
        }
        .center {
            width: 280px;
            margin: 0 auto;
            height: 400px;
            overflow-y: scroll;
            p {
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                span {
                    width: 80px;
                    text-align: center;
                    height: 50px;
                    line-height: 50px;
                }
            }
            div {
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
            }
        }
        .center::-webkit-scrollbar {
            display: none;
        }
        .ipt {
            width: 280px;
            margin: 0 auto;
            display: flex;
            justify-content: flex-start;
            height: 50px;
            align-items: center;
            span {
                width: 90px;
            }
        }
        .bottom {
            width: 200px;
            position: absolute;
            bottom: 20px;
            left: 50px;
        }
    }
}
.searchAddress{
    width: 300px;
    position: absolute;
    top: 5px;
    left: 300px;
    display: flex;
    justify-content: space-between;
}
.box{
    width: 120px;
    height: 100px;
    border-radius: 10px;
    background: #fff;
    position: absolute;
    bottom: 30px;
    right: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}
</style>
